package top.techqi.usbd.finder

import android.hardware.usb.UsbDevice
import android.util.SparseArray
import top.techqi.core.util.ResUtil
import top.techqi.usbd.R
import top.techqi.usbd.UsbDefine
import top.techqi.usbd.UsbDriver
import top.techqi.usbd.UsbFinder
import top.techqi.usbd.driver.serial.CdcAcmSerialDriver

object CdcAcmFinder : UsbFinder {
    override fun detectDrivers(
        device: UsbDevice,
        remains: MutableSet<Int>,
        drivers: SparseArray<Pair<String, Class<out UsbDriver>>>
    ): Int {
        if (device.deviceClass != UsbDefine.DEVICE_CLASS.CDC &&
            device.deviceClass != UsbDefine.DEVICE_CLASS.MDC
        ) return 0

        var count = 0
        val intfCount = device.interfaceCount
        for (index in 0..<intfCount) {
            val intf = device.getInterface(index)
            if (intf.interfaceClass == UsbDefine.INTF_CLASS.CDC_COMM
                && intf.interfaceSubclass == UsbDefine.INTF_SUBCLASS.CDM_ACM
            ) {
                remains.remove(intf.id)
            } else if (intf.interfaceClass == UsbDefine.INTF_CLASS.CDC_DATA) {
                remains.remove(intf.id)

                var name = intf.name ?: ""
                if (name.isBlank()) {
                    name = ResUtil.getString(R.string.usbd_driver_cdcacm_portname, count)
                }
                drivers.put(
                    device.getInterface(index).id,
                    Pair(name, CdcAcmSerialDriver::class.java)
                )
                count += 1
            }
        }

        return count
    }
}
